package com.example.helloworld

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.google.android.material.snackbar.Snackbar

class GeneralTimerFragment : Fragment() {
    private var isTimerRunning = false
    private var elapsedTimeMillis = 0L
    private val handler = Handler(Looper.getMainLooper())
    private lateinit var timerTextView: TextView
    private lateinit var textView: TextView
    private lateinit var startButton: Button
    
    private val timerRunnable = object : Runnable {
        override fun run() {
            if (isTimerRunning) {
                elapsedTimeMillis += 100 // 每100ms更新一次
                updateTimerDisplay()
                handler.postDelayed(this, 100)
            }
        }
    }

    private fun updateTimerDisplay() {
        val totalSeconds = elapsedTimeMillis / 1000.0
        val minutes = totalSeconds.toInt() / 60
        val seconds = totalSeconds.toInt() % 60
        val millis = (elapsedTimeMillis % 1000) / 10 // 取两位小数
        
        timerTextView.text = String.format("%02d:%02d.%02d", minutes, seconds, millis)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_general_timer, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        textView = view.findViewById(R.id.textView)
        startButton = view.findViewById(R.id.changeTextButton)
        val resetButton = view.findViewById<Button>(R.id.resetButton)
        val saveButton = view.findViewById<Button>(R.id.saveButton)
        val historyButton = view.findViewById<Button>(R.id.historyButton)
        timerTextView = view.findViewById(R.id.timerTextView)
        
        updateTimerDisplay()

        startButton.setOnClickListener {
            if (!isTimerRunning) {
                isTimerRunning = true
                startButton.text = "停止计时"
                handler.post(timerRunnable)
            } else {
                isTimerRunning = false
                startButton.text = "开始计时"
                handler.removeCallbacks(timerRunnable)
            }
            textView.text = "计时器已" + if (isTimerRunning) "开始" else "停止"
        }

        resetButton.setOnClickListener {
            isTimerRunning = false
            elapsedTimeMillis = 0
            startButton.text = "开始计时"
            handler.removeCallbacks(timerRunnable)
            updateTimerDisplay()
            textView.text = "计时器已重置"
        }

        saveButton.setOnClickListener {
            val currentTime = System.currentTimeMillis()
            val record = TimerRecord(
                duration = elapsedTimeMillis / 1000.0,
                savedTime = currentTime
            )
            saveRecord(record)
            Snackbar.make(view, "记录已保存", Snackbar.LENGTH_SHORT).show()
        }

        historyButton.setOnClickListener {
            startActivity(Intent(requireContext(), HistoryActivity::class.java))
        }
    }

    private fun saveRecord(record: TimerRecord) {
        val prefs = requireActivity().getSharedPreferences("timer_records", android.content.Context.MODE_PRIVATE)
        val json = prefs.getString("records", "[]")
        val type = object : TypeToken<MutableList<TimerRecord>>() {}.type
        val records = Gson().fromJson<MutableList<TimerRecord>>(json, type)
        records.add(record)
        
        prefs.edit()
            .putString("records", Gson().toJson(records))
            .apply()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        handler.removeCallbacks(timerRunnable)
    }
} 